#include "my_headerT2csJ.h"

int exitpipe[2];

void sigfunc(int ret){
    printf("sigfun arg:%d\n",ret);
    printf("all will gone...\n");
    write(exitpipe[1],"1",1);
}

/* Usage:  */
int main(int argc, char *argv[]){                                  
    ARGS_CHECK(argc,4);
    pipe(exitpipe);
    
    if(fork()){
        close(exitpipe[0]);
        signal(SIGUSR1,sigfunc);
        wait(NULL);
        exit(0);
    }

    close(exitpipe[1]);
    int workernum = atoi(argv[3]);
    threadPoll_t tpt;
    init_thread_pool(&tpt,workernum);
    make_worker(workernum,&tpt);
    int skd = init_Tcp(argv[1],argv[2]);

    int epfd= epoll_create(1);
    struct epoll_event epets[1024];
    /* epoll_ctl(epfd,EPOLL_CTL_ADD,skd,&epet); */
    epoll_add(epfd,skd);
    epoll_add(epfd,exitpipe[0]);

    while(1){
        memset(epets,-1,sizeof(epets));
        int ewRet = epoll_wait(epfd,epets,1,-1);
        printf("main.ewRet:%d\n",ewRet);
        if(epets[0].data.fd == skd){
            int netfd = accept(skd,NULL,NULL);
            pthread_mutex_lock(&tpt.pmt);
            printf("recv netfd %d\n",netfd);
            tailAdd(&tpt.ltt,netfd);
            pthread_cond_broadcast(&tpt.pct);
            pthread_mutex_unlock(&tpt.pmt);
        }
        else if(epets[0].data.fd == exitpipe[0]){
            pthread_mutex_lock(&tpt.pmt);
            tpt.flag = 1;
            pthread_cond_broadcast(&tpt.pct);
            pthread_mutex_unlock(&tpt.pmt);
            for(int i = 0;i<workernum;i++){
                pthread_join(tpt.wkt.workers[i],NULL);
                printf("recv worker %d\n",i);
            }
            exit(0);
        }
    }

    return 0;
}

